<template>
    <div class="content">
        <el-dialog :visible.sync="batchBind.dialogFormVisible"
        title="批量绑定" size="tiny" :before-close="handleClose">
            <el-tabs class="titleTap">
                <el-tab-pane label="IC、ID、双频卡">
                    <div v-loading = "upLoading">
                        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="170px">
                                <el-row :gutter="20" type="flex" justify="space-between">
                                    <el-col :span="20">
                                        <el-form-item label="选择学校：" prop="schoolName">
                                            <school v-model="ruleForm.schoolName" style="width:100%" @getSchoolInfor='schoolChange' @change = "schoolVerify"></school>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="20">
                                        <el-form-item v-if="schoolType === '0'" label="选择年级：" prop="sGrade">
                                            <el-select v-model="ruleForm.sGrade" placeholder="请选择添加的年级" style="width:100%;" @change="queryAllClass( ruleForm.sGrade )">
                                                <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="20">
                                        <el-form-item label="选择班级：" prop="sClass">
                                            <el-select v-model="ruleForm.sClass" placeholder="请选择添加的班级" style="width:100%;">
                                                <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col align="center">
                                        <span class="downloadTip" @click="downloadModule">请先选择学校、年级、班级后下载班级专属批量绑卡模板</span>
                                    </el-col>
                                </el-row>
                            <el-form-item label="选择导入的Excel文件：">
                            <el-row :gutter="20" type="flex" justify="space-between">
                                <el-col :span="20">

                                <span class="urlText" v-cloak>
                                    <el-row type="flex" class="row-bg" justify="space-between">
                                    <el-col :span="6">
                                        <el-button type="text" class="text">{{form.text}}</el-button>
                                    </el-col>
                                    <span>
                                        <el-button v-if="delStart" @click="delFileUrl" type="text">
                                        删除<i class="el-icon-close el-icon--right"></i>
                                        </el-button>
                                    </span>
                                    </el-row>
                                    <i v-if="expand" :style="`width:${progress}%`" class="expand"></i>
                                </span>
                                </el-col>
                                <span>
                                <template v-if="disabled && schoolType === '0' && ruleForm.sClass || disabled && schoolType === '1'">
                                    
                                    <file-upload ref="upload" @onSuccess="successFn" :isAuto="true" @getFileName="getFileName"  @onProgress="progressFn" :up-file-type="fileOptions.upFileType">
                                        <el-button  type="text" class="btn-success font-style-color" slot="trigger" size="small">选择文件</el-button>
                                    </file-upload>
                                </template>
                                <template v-else>
                                    <el-button type="text" class="btn-success font-style-color" @click="upTrigger"  size="small">选择文件</el-button>
                                </template>
                                </span>
                            </el-row>
                            </el-form-item>
                            <div v-if="percentage == 100">
                                <div v-if="delStart">
                                    <el-form-item label="校验结果：">
                                    <p>数据无误，可上传！</p>
                                    </el-form-item>
                                </div>
                            </div>
                            <div v-else>
                                <div v-if="delStart">
                                    <el-form-item label="校验结果：">
                                        <span class="title">数据校验中</span>
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <el-progress :percentage="percentage"></el-progress>
                                            </el-col>
                                        </el-row>
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <p>{{errorIng}}</p>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                            <div v-if="upError">
                                <el-form-item label="错误信息：">
                                    <el-row :gutter="20">
                                    <el-col :span="20">
                                        <p>{{errorIng}}</p>
                                    </el-col>
                                    </el-row>
                                </el-form-item>
                            </div>
                        </el-form>
                        <footer>
                            <el-button @click="cancel('ruleForm')">取消</el-button>
                            <el-button :disabled="percentage !== 100" :loading="loading" @click="add('ruleForm')" type="primary">确认</el-button>
                        </footer>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="虚拟卡">
                    <div v-loading = "upLoading">
                        <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="170px">
                                <el-row :gutter="20" type="flex" justify="space-between">
                                    <el-col :span="20">
                                        <el-form-item label="选择学校：" prop="schoolName">
                                            <school v-model="dataForm.schoolName" style="width:100%" @getSchoolInfor='verschoolChange' @change = "verschoolVerify"></school>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="20">
                                        <el-form-item v-if="schoolType2 === '0'" label="选择年级：" prop="sGrade">
                                            <el-select v-model="dataForm.sGrade" placeholder="请选择添加的年级" style="width:100%;" @change="queryAllClass2( dataForm.sGrade )">
                                                <el-option v-for="item in gradeList2" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="20">
                                        <el-form-item label="选择班级：" prop="sClass">
                                            <el-select v-model="dataForm.sClass" placeholder="请选择添加的班级" style="width:100%;">
                                                <el-option v-for="item in classList2" :key="item.classId" :label="item.className" :value="item.classId">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col align="center">
                                        <span class="vertivalTip" v-show="showVerTip">学校未添加人脸识别设备，请先添加设备~</span>
                                    </el-col>
                                </el-row>
                        </el-form>
                        <footer>
                            <el-button @click="cancel('dataForm')">取消</el-button>
                            <el-button @click="addvertivalCard('dataForm')" type="primary">绑定</el-button>
                        </footer>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>
<script>
import { getGrade } from 'api/classAll';
import { getClass, listSysDictByType, verifyClassStudent, verifyStudentCardForImport, importStudentCard, importStudentVirtualCard } from 'api/cardMangement';
import school from 'components/SchoolClasss/school';
import fileUpload from 'components/Upload/fileUpload';
import { mapGetters } from 'vuex';
export default {
    name: 'addClassSchool',
    components: { school, fileUpload },
    props: {
        batchBind: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            fileObj: {},
    // 设置上传类型
            fileOptions: {
                upFileType: 'excel'
            },

    // 初始加载进度
            progress: 0,

    // 展示上传文件名称
            form: {
                text: ''
            },

    // 判断是否选择文件
            delStart: false,

    // 是否进度条滚动
            expand: false,

    // 上传loading
            loading: false,
            disabled: false,
            percentage: 0,
            timout: null,
            errorIng: '',
            upError: false,


            upLoading: false,
            gradeList: [],
            classList: [],
            gradeList2: [],
            classList2: [],
            relationList: [],
            autoFill: false,
            showVerTip: false,
            newSchoolId: '',
            newSchoolId2: '',
            ruleForm: {
                schoolName: '',
                schoolId: '',
                sGrade: '',
                sClass: '',
                studentName: '',
                cardNum: '',
                sCardType: '',
                sRelationType: '',
                sRelation: ''
            },
            dataForm: {
                schoolName: '',
                schoolId: '',
                sGrade: '',
                sClass: ''
            },
            schoolList: [],
        // 是否培训和普通学校  1 0
            schoolType: '0',
            schoolType2: '0',
            rulesSeletarea: {
                validator: (rule, value, callback) => {
                    if (!this.ruleForm.areaId && !value) {
                        callback(new Error('请选择'));
                    } else {
                        callback();
                    }
                },
                trigger: 'change'
            },
            rules: {
                schoolName: [
                { required: true, message: '请输入学校名称', trigger: 'blur' }
                ],
                sGrade: [
                { required: true, message: '请输入年级', trigger: 'change' }
                ],
                sClass: [
                { required: true, message: '请输入班级', trigger: 'change' }
                ],
                studentName: [
                { required: true, message: '请输入学生姓名', trigger: 'blur' }
                ],
                cardNum: [
                { required: true, message: '请输入卡号', trigger: 'blur' }
                ]
            
            }
        };
    },
    computed: {
        ...mapGetters(['token'])
    },
    created() {
        this.listSysDictByType();
    },
    watch: {
        'ruleForm.schoolId': {
            handler(val, oldVal) {
                console.log('val', val, 'oldVal', oldVal);
                if (val) {
                    this.disabled = true;
                }
            },
            deep: true
        }
    },
    methods: {

        progressFn(p) {
            this.progress = p.percent;
            this.expand = true;
        },

        progressIng(boolean) {
            if (boolean) {
                this.timout = setInterval(() => {
                    if (this.percentage <= (85 + Math.round(Math.random()*10))) {
                        this.percentage += Math.round(Math.random()*6)
                    } else {
                        clearInterval(this.timout);
                    }
                }, 500)
            } else {
                clearInterval(this.timout);
            }
        },

        upTrigger() {
            if (this.schoolType === '0' && this.ruleForm.sClass === '') {
                // this.$refs.ruleForm.validateField('sGrade');
                // this.$refs.ruleForm.validateField('sClass');
                this.$message('请先选择年级和班级');
            }
            this.$refs.ruleForm.validateField('schoolName');

        },

        successFn(obj) {
            this.upTrigger();

            // 判断是否拿到回调值
            this.upError = false;
            this.fileObj=obj;
            this.progressIng(true);
            // 触发上传事件
            if (!this.fileObj.fileName) {
                this.$message({
                    message: '请先上传文件',
                    type: 'warning'
                });
            } else {
                this.loading = true;
                let schoolId = this.ruleForm.schoolId;
                if (schoolId) {// 如果有该学校
                    
                    verifyStudentCardForImport(this.ruleForm.schoolId, this.ruleForm.sClass, this.fileObj.imgUrl, this.ruleForm.schoolName).then(response => {
                        this.loading = false;
                        this.percentage = 100;
                        this.progressIng(false);
                        this.$message({
                            message: '上传成功！',
                            type: 'success'
                        });
                    }).catch(Error => {
                        this.errorIng = Error;
                        this.progressIng(false);
                    });

                }
            }
        },
        getFileName(obj) {
            this.form.text = obj.name;
            this.delStart = true;
        },

        delFileUrl() {
            // this.ruleForm.schoolId = '';
            // this.ruleForm.schoolName = '';// 清空学校
            // this.ruleForm.sGrade = '';
            // this.ruleForm.sClass = '';
            this.fileObj='';
            this.form.text = '';
            this.delStart = false;
            this.expand = false;
            this.loading = false;
            // this.disabled = false;
            clearInterval(this.timout);
            this.percentage = 0;
            this.upError = false;
        },

        schoolVerify(val) {
            if (!val) {
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';
            }
        },

        verschoolVerify(val) {
            if (!val) {
                this.gradeList2 = [];
                this.classList2 = [];
                this.dataForm.sGrade = '';
                this.dataForm.sClass = '';
            }
        },

        // 获取学校id
        schoolChange(val) {
        
            if (this.ruleForm.schoolId !== val.schoolId) {
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';
            }
            this.ruleForm.schoolId = val.schoolId;
            
            this.getSecInfo(val);
        },

        // 获取学校id
        verschoolChange(val) {
            console.log('val', val);
            if (this.dataForm.schoolId !== val.schoolId) {
                this.gradeList2 = [];
                this.classList2 = [];
                this.dataForm.sGrade = '';
                this.dataForm.sClass = '';
            }
            this.dataForm.schoolId = val.schoolId;

            this.getverSecInfo(val);
        },

        getSecInfo(val) {
            // 判断用户是否确认选择
            console.log('val', val);
            if (val.schoolId) {
                if (this.ruleForm.schoolId !== val.schoolId) {
                    
                    this.gradeList = [];
                    this.classList = [];
                    this.ruleForm.sGrade = '';
                    this.ruleForm.sClass = '';
                }
                this.judgmentSta(val);
                // 填充省市区
                this.ruleForm.provinceId = val.provinceId;
                this.ruleForm.cityId = val.cityId;
                this.ruleForm.areaId = val.areaId;
                
            } else {
                this.schoolList = [];
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.schoolName = '';
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';
            }
            
            this.autoFill = true;
            this.$nextTick(() => {
                this.autoFill = false;
            });
            this.getGradeName = '';
            this.newSchoolId = val.schoolId;
            if (val.schoolId) {
                if (this.schoolType === '0') {
                    getGrade(!val.schoolId ? null : val.schoolId).then(response => {
                        this.gradeList = response.data.content;
                    });
                } else {
                    this.queryAllClass('');
                }
                
            }
        },

        getverSecInfo(val) {
            // 判断用户是否确认选择
            
            if (val.schoolId) {
                if (this.dataForm.schoolId !== val.schoolId) {
                    
                    this.gradeList2 = [];
                    this.classList2 = [];
                    this.dataForm.sGrade = '';
                    this.dataForm.sClass = '';
                }
                this.judgmentSta2(val);
                // 填充省市区
                // this.dataForm.provinceId = val.provinceId;
                // this.dataForm.cityId = val.cityId;
                // this.dataForm.areaId = val.areaId;
                
            } else {
                this.schoolList = [];
                this.gradeList2 = [];
                this.classList2 = [];
                this.dataForm.schoolName = '';
                this.dataForm.sGrade = '';
                this.dataForm.sClass = '';
            }
            
            // this.autoFill = true;
            // this.$nextTick(() => {
            //     this.autoFill = false;
            // });
            this.getGradeName = '';
            this.newSchoolId2 = val.schoolId;
            console.log('val2222', val.schoolId);
            if (val.schoolId) {
                if (this.schoolType2 === '0') {
                    getGrade(!val.schoolId ? null : val.schoolId).then(response => {
                        this.gradeList2 = response.data.content;
                    });
                } else {
                    this.queryAllClass2('');
                }
            }
        },

        downloadModule() {
            let className = '';
            this.classList.forEach(item => {
                if (this.ruleForm.sClass == item.classId) {
                    return className = item.className;
                }
            });
            if (!this.token || this.ruleForm.sClass === '' || this.ruleForm.schoolName === '' || className === '') {
                this.$message('请先填写完整信息');
                return;
            } else {   
                verifyClassStudent(this.token, this.ruleForm.sClass).then((res) => {
                    console.log('res', res.data.content);
                    if (res.data.content > 0) {
                        window.location.href = `${LOCAL_API.fyq}/card/expotClassInfo?token=${this.token}&classId=${this.ruleForm.sClass}&schoolName=${this.ruleForm.schoolName}&className=${className}`;
                    } else {
                        this.$message('您选择的班级没有学生');
                    }
                }).catch((res) => {
                    this.$message('error');
                })
                // window.location.href = `${LOCAL_API.fyq}/card/expotClassInfo?token=${this.token}&classId=${this.ruleForm.sClass}&schoolName=${this.ruleForm.schoolName}&className=${className}`;
            }
        },

        // 判断是否普通学校/培训学校
        judgmentSta(val) {
            this.schoolType = val.schoolType;
            // this.schoolList.forEach(item => {
            //     if (val === item.schoolId) {
            //         console.log('item', item.schoolType);
            //         this.schoolType = item.schoolType;
            //     }
            // });
        },

        judgmentSta2(val) {
            this.schoolType2 = val.schoolType;
            // this.schoolList.forEach(item => {
            //     if (val === item.schoolId) {
            //         this.schoolType = item.schoolType;
            //     }
            // });
        },

        // 年级列表
        queryAllGrade(val) {
            // 判断用户是否确认选择
            if (val.schoolId) {
                this.ruleForm.schoolId = val.schoolId;
                this.judgmentSta(val);
                // 填充省市区
                let school = this.schoolList.find(s => s.schoolId == val.schoolId);
                this.ruleForm.provinceId = school.provinceId;
                this.ruleForm.cityId = school.cityId;
                this.ruleForm.areaId = school.areaId;
            } else {
                this.schoolList = [];
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.schoolName = '';
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';

            }

            this.autoFill = true;
            this.$nextTick(() => {
                this.autoFill = false;
            });
            this.getGradeName = '';
            this.newSchoolId = val.schoolId;
            if (val.schoolId) {
                getGrade(!val.schoolId ? null : val.schoolId).then(response => {
                    this.gradeList = response.data.content;
                    this.classList = [];
                    this.ruleForm.sClass = '';
                });
            }
        },

        // 班级列表
        queryAllClass(gradeId) {
            this.classList = [];
            this.ruleForm.sClass = '';
            getClass(
                !this.newSchoolId ? null : this.newSchoolId,
                !gradeId ? null : gradeId
            ).then(response => {
                this.classList = response.data.content;
            });
        },

        queryAllClass2(gradeId) {
            console.log('gradeId', gradeId);
            this.classList2 = [];
            this.ruleForm.sClass = '';
            getClass(
                !this.newSchoolId2 ? null : this.newSchoolId2,
                !gradeId ? null : gradeId
            ).then(response => {
                this.classList2 = response.data.content;
            });
        },

        // 关系列表
        listSysDictByType() {
            listSysDictByType().then((res) => {
                this.relationList = res.data.content;
            })
        },

        add(ruleForm) {
            this.$refs[ruleForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {
                    this.upLoading = true;

                    let sClass = this.ruleForm.sClass;
                    if (sClass) {// 如果有该班级                   
                        importStudentCard(this.ruleForm.schoolId, this.ruleForm.sClass).then(res => {
                            this.upLoading = false;
                            this.handleClose();
                            /**
                             * edit by cuihd at 20180712
                             * 给父组件传值$emit
                             * 将获取的res复制到一个新的对象，其中包括轮询所需要的参数
                             */
                            let newObj = {};
                            for (let x in res.data.content) {
                                newObj[x] = res.data.content[x];
                            }
                            newObj.isTrue = true; 
                            newObj.state = '1';
                            this.$emit('importCardState', newObj);
                        }).catch(Error => {
                            this.upLoading = false;
                        });
                    } 
                }
            });
        },

        addvertivalCard(dataForm) {
            // if (this.dataForm.sGrade === '' || this.dataForm.sClass === '') {
                
            //     return;
            // }
            // this.showVerTip = true;
            // this.$emit('showBindInfo', true);
            // this.dialog.showBindInfo = true;
            this.$refs[dataForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {

                    this.loading2 = true;
                    importStudentVirtualCard(this.dataForm.schoolId, this.dataForm.sClass, this.dataForm.schoolName).then(res => {
                        this.loading2 = false;
                        this.handleClose();
                        this.$emit('update:visible', !this.visible);
                        /**
                         * edit by cuihd at 20180712
                         * 给父组件传值$emit
                         * 将获取的res复制到一个新的对象，其中包括轮询所需要的参数
                         */
                        let newObj = {};
                        for (let x in res.data.content) {
                            newObj[x] = res.data.content[x];
                        }
                        newObj.isTrue = true; 
                        newObj.state = '0';
                        this.$emit('importCardState', newObj);
                    }).catch(Error => {
                        this.loading2 = false;
                        // this.$message(Error);
                    });

                }
            });
            
        },

        handleClose() {
            this.$refs.ruleForm.resetFields();
            this.$refs.dataForm.resetFields();
            this.delFileUrl();
            this.ruleForm.schoolId = '';
            this.ruleForm.sGrade = '';
            this.ruleForm.sClass = '';
            this.dataForm.schoolId = '';
            this.dataForm.sGrade = '';
            this.dataForm.sClass = '';
            this.batchBind.dialogFormVisible = false;
        },

        cleanData() {
            this.$refs.ruleForm.resetFields();
            this.$refs.dataForm.resetFields();
            this.delFileUrl();
            this.ruleForm.schoolId = '';
            this.ruleForm.sGrade = '';
            this.ruleForm.sClass = '';
            this.dataForm.schoolId = '';
            this.dataForm.sGrade = '';
            this.dataForm.sClass = '';
        },
        
        cancel() {
            this.$refs.ruleForm.resetFields();
            this.$refs.dataForm.resetFields();
            this.delFileUrl();
            this.ruleForm.schoolId = '';
            this.ruleForm.sGrade = '';
            this.ruleForm.sClass = '';
            this.dataForm.schoolId = '';
            this.dataForm.sGrade = '';
            this.dataForm.sClass = '';
            this.batchBind.dialogFormVisible = false;
        }
    }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}
.tip{
  padding: 5px 0;
  color: #ccc;
  line-height: 18px;
}
.downloadTip{
    position: relative;
    top: -10px;
    color: #37a1fb;
    text-align: center;
    cursor: pointer;
}
.urlText {
  position: relative;
  height: 36px;
  width: 100%;
  display: block;
  border: 1px solid rgb(217, 200, 191);
  padding: 0 10px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  .text {
    width: 155px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .expand {
    position: absolute;
    width: 100%;
    height: 1px;
    margin: 2px 0;
    background: #37a1fb;
    bottom: -3px;
    left: 0;
    transition: all 5s;
  }
}
footer {
  text-align: center;
}
</style>
